package cn.micro.keep.accounts.common.log.aspect;




import cn.micro.keep.accounts.common.log.annotation.Log;
import cn.micro.keep.accounts.common.log.entity.SysOperLog;
import cn.micro.keep.accounts.common.log.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class LogAspect {


    //环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog) {
        //业务方法调用之前，封装数据
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog,joinPoint,sysOperLog);
        //业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            //调用业务方法之后，封装数据
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,0,null);
        } catch (Throwable e) {
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,1,e.getMessage());
            //抛出运行时异常
            throw new RuntimeException(e.getMessage());
        }finally {
            //调用service方法把日志信息添加数据库里面
            //打印出来
            log.info("用户操作日志信息：用户名为：{}，操作日志为：{}",sysOperLog.getOperName(), sysOperLog);
        }
        return proceed;
    }
}
